package com.firewolf.dto;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class MainDriver {

	private EntityManagerFactory factory = null;
	private EntityManager manager = null;
	private EntityTransaction tx = null;

	@Before
	public void init() {
		factory = Persistence.createEntityManagerFactory("jpa");
		manager = factory.createEntityManager();
		tx = manager.getTransaction();
		tx.begin();
	}

	@After
	public void destory() {
		tx.commit();
		manager.close();
		factory.close();
	}

	@Test
	public void generateTable() {
	}

	@Test
	public void save() {
		News n = new News();
		n.setContent("内容");
		n.setTitle("主题");
		manager.persist(n);
	}

	/**
	 * 默认情况下，一级缓存是开启了的，
	 */
	@Test
	public void oneLevelCache() {
		News n = manager.find(News.class, 1);
		System.out.println(n);
		News n2 = manager.find(News.class, 1);
		System.out.println(n2);
	}

	/**
	 * 默认情况下，关闭session再次开启session的话，查询会发送SQL语句，
	 * 也就是说，关闭session的时候，缓存清空，
	 * 开启二级缓存之后，就不会再次查询了
	 */
	@Test
	public void secondLevelCache() {
		News n = manager.find(News.class, 1);
		System.out.println(n);
		manager.close();
		manager = factory.createEntityManager();
		News n2 = manager.find(News.class, 1);
		System.out.println(n2);
		
	}

}
